package com.csx.framework.netty.sample.aio.server;

import com.csx.framework.netty.sample.aio.ChannelAdapter;
import com.csx.framework.netty.sample.aio.ChannelHandler;

import java.net.SocketAddress;
import java.nio.channels.AsynchronousSocketChannel;
import java.nio.charset.Charset;
import java.util.Date;

/**
 * <p> what does this class do ? </p>
 * <p> How does it work ?</p>
 * <p> Why does it do this ?</p>
 *
 * @author cuisongxu
 * @date 2023/8/8 周二 18:49
 */
public class AioServerHandler extends ChannelAdapter {

    public AioServerHandler(AsynchronousSocketChannel channel, Charset charset) {
        super(channel, charset);
    }

    @Override
    public void channelActive(ChannelHandler ctx) {
        try {
            SocketAddress remoteAddress = ctx.channel().getRemoteAddress();
            System.out.println("服务端连接成功: remoteAddress: " + remoteAddress);
            ctx.writeAndFlush("当前 服务端连接成功: remoteAddress: "  + remoteAddress);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    @Override
    public void channelInactive(ChannelHandler ctx) {

    }

    @Override
    public void channelRead(ChannelHandler ctx, Object msg) {
        ctx.writeAndFlush("时间: " + new Date() + " 接收到消息: " + msg);
    }
}
